import 'dart:io';

import 'package:file_saver/file_saver.dart';
import 'package:file_selector/file_selector.dart';
import 'package:filelinker/mdsn.dart';
import 'package:filelinker/netsev.dart';
import 'package:flutter/material.dart';
import 'package:gap/gap.dart';

class SettingPage extends StatefulWidget {
  const SettingPage({super.key, this.showAddFolder = false});

  final bool showAddFolder;

  @override
  State<SettingPage> createState() => _SettingPageState();
}

class _SettingPageState extends State<SettingPage> {
  int _year = 2024;

  @override
  void initState() {
    super.initState();
    _year = DateTime.now().year;
    if (mounted) setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    bool isDesktop = MDNS.shared.isDesktop;
    return Scaffold(
      appBar: AppBar(
        leading: isDesktop ? const CloseButton() : null,
        title: isDesktop ? null : const Text("设置"),
      ),
      body: _wBodyView(),
    );
  }

  Widget _wBodyView() {
    return Container(
      margin: const EdgeInsets.symmetric(horizontal: 20),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          const Gap(70),
          ClipRRect(
            borderRadius: BorderRadius.circular(15),
            child: SizedBox.fromSize(
              size: const Size(80, 80),
              child: Image.asset(
                "assets/images/logo.webp",
              ),
            ),
          ),
          const Gap(20),
          Text(
            "FileLinker",
            style: Theme.of(context).textTheme.titleLarge,
          ),
          const Gap(10),
          Text(
            "1.0.0",
            style: Theme.of(context).textTheme.titleSmall,
          ),
          _wDownloadFolderView(),
          const Gap(20),
          _wServInfoView(),
          const Spacer(),
          Center(
            child: Text(
              "©$_year All rights reserved — Limbo Naiso",
              style: TextStyle(
                color: Theme.of(context).colorScheme.secondary.withAlpha((0.25 * 255).round()),
                fontSize: 10,
              ),
            ),
          ),
          const Gap(20),
        ],
      ),
    );
  }

  Widget _wDownloadFolderView() {
    if (Platform.isIOS) {
      return Container();
    }
    return Container(
      constraints: const BoxConstraints(minHeight: 40),
      margin: const EdgeInsets.only(top: 20),
      child: Row(
        children: [
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  "下载文件夹：",
                  style: Theme.of(context).textTheme.titleMedium,
                ),
                Text(
                  NetService.shared.downloadFolder,
                  style: Theme.of(context).textTheme.bodySmall,
                ),
              ],
            ),
          ),
          const Gap(20),
          IconButton(
            icon: Icon(
              MDNS.shared.isDesktop ? Icons.create_new_folder : Icons.folder_open,
            ),
            onPressed: _didTapOpenFolder,
          ),
        ],
      ),
    );
  }

  Widget _wServInfoView() {
    return Text.rich(TextSpan(
      children: [
        const TextSpan(
          text: "本地服务端口: ",
        ),
        TextSpan(
          text: "${MDNS.shared.port}",
          style: TextStyle(
            color: Theme.of(context).colorScheme.secondary,
            fontSize: 10,
          ),
        ),
      ],
      style: TextStyle(
        color: Theme.of(context).colorScheme.secondary,
        fontSize: 12,
      ),
    ));
  }

  void _didTapOpenFolder() async {
    if (Platform.isAndroid) {
      FileSaver.instance.openFolder(NetService.shared.downloadFolder);
      return;
    }
    final folder = await getDirectoryPath(initialDirectory: NetService.shared.downloadFolder);
    if (folder != null && folder.isNotEmpty) {
      await NetService.shared.updateDownloadFolder(folder);
      setState(() {});
    }
    debugPrint("folder: $folder");
  }
}
